package com.ruoyi.forum.controller;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.forum.api.vo.ReplyItem;
import com.ruoyi.forum.api.vo.UserDetail;
import com.ruoyi.forum.constant.TopicReplyTypeEnum;
import com.ruoyi.forum.domain.CircleTopic;
import com.ruoyi.forum.domain.CircleTopicReply;
import com.ruoyi.forum.service.AuthServiceExt;
import com.ruoyi.forum.service.CircleBlacklistService;
import com.ruoyi.forum.service.CircleTopicReplyService;
import com.ruoyi.forum.service.CircleTopicService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Tag(name = "论坛评论", description = "论坛评论管理接口")
@RequestMapping(value = "/circle")
@RestController
public class CircleReplyController extends BaseController {

    @Autowired
    private DozerBeanMapper mapper;

    @Autowired
    private AuthServiceExt authServiceExt;

    @Autowired
    private CircleTopicService circleTopicService;

    @Autowired
    private CircleTopicReplyService circleTopicReplyService;


    @Autowired
    private CircleBlacklistService blacklistService;

    @Operation(summary = "点赞", description = "点赞")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
            @Parameter(name = "uid", description = "用户id", required = true)
    })
    @RequestMapping(value = "/topic/great", method = RequestMethod.POST)
    public AjaxResult greatTopic(@RequestParam(value = "id") Long id,
                                 @RequestParam(value = "uid") String uid) {
        try {
            blacklistService.checkLimit(uid);
            CircleTopic circleTopic = circleTopicService.getById(id);
            if (circleTopic == null) {
                return AjaxResult.error("对象信息不存在");
            }
            if (circleTopic.getDelFlag() != null && circleTopic.getDelFlag() == 1) {
                return AjaxResult.error("该动态已被删除！");
            }

            // 使用 LambdaQueryWrapper 构造查询条件
            LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CircleTopicReply::getDelFlag, 0)
                    .eq(CircleTopicReply::getUid, uid)
                    .eq(CircleTopicReply::getReplyType, TopicReplyTypeEnum.GREAT.value())
                    .eq(CircleTopicReply::getTopicId, circleTopic.getId());

// 执行查询
            List<CircleTopicReply> replys = circleTopicReplyService.list(wrapper);
            if (replys != null && replys.size() > 0) {
                return AjaxResult.error("操作过于频繁");
            }

            // 使用 LambdaQueryWrapper 构造查询条件
            LambdaQueryWrapper<CircleTopicReply> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(CircleTopicReply::getDelFlag, 1)
                    .eq(CircleTopicReply::getUid, uid)
                    .eq(CircleTopicReply::getReplyType, TopicReplyTypeEnum.GREAT.value())
                    .eq(CircleTopicReply::getTopicId, circleTopic.getId());

// 执行查询
            replys = circleTopicReplyService.list(wrapper2);

            if (replys == null || replys.size() == 0) {
                CircleTopicReply reply = new CircleTopicReply();
                circleTopic.setGreatNum(circleTopic.getGreatNum() + 1);
                reply.setCreateTime(System.currentTimeMillis());
                reply.setTopicId(circleTopic.getId());
                reply.setUid(uid);
                reply.setDelFlag(0);
                reply.setReplyType(TopicReplyTypeEnum.GREAT.value());
                reply.setTopFlag(0);
                if (uid.equals(circleTopic.getUid())) {
                    reply.setReadFlag(1);
                } else {
                    reply.setReadFlag(0);
                }
                reply.setTopicId(id);
                circleTopicService.great(circleTopic, reply);
            } else {
                CircleTopicReply reply = replys.get(0);
                circleTopic.setGreatNum(circleTopic.getGreatNum() + 1);
                reply.setCreateTime(System.currentTimeMillis());
                reply.setDelFlag(0);
                if (uid.equals(circleTopic.getUid())) {
                    reply.setReadFlag(1);
                } else {
                    reply.setReadFlag(0);
                }
                circleTopicService.great(circleTopic, reply);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }


    }

    @Operation(summary = "取消点赞", description = "取消点赞")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
            @Parameter(name = "uid", description = "用户id", required = true)
    })
    @RequestMapping(value = "/topic/ungreat", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult ungreatTopic(@RequestParam(value = "id") Long id,
                                   @RequestParam(value = "uid") String uid) {
        try {
            blacklistService.checkLimit(uid);
            CircleTopic circleTopic = circleTopicService.getById(id);
            if (circleTopic == null) {
                return AjaxResult.error("对象信息不存在");
            }
            if (circleTopic.getDelFlag() != null && circleTopic.getDelFlag() == 1) {
                return AjaxResult.error("该动态已被删除！");
            }
            circleTopic.setGreatNum(circleTopic.getGreatNum() - 1);


            // 使用 LambdaQueryWrapper 构造查询条件
            LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CircleTopicReply::getDelFlag, 0)
                    .eq(CircleTopicReply::getUid, uid)
                    .eq(CircleTopicReply::getReplyType, TopicReplyTypeEnum.GREAT.value())
                    .eq(CircleTopicReply::getTopicId, circleTopic.getId());

// 执行查询
            List<CircleTopicReply> replys = circleTopicReplyService.list(wrapper);


            if (replys != null && replys.size() > 0) {
                CircleTopicReply reply = replys.get(0);
                reply.setDelFlag(1);
                circleTopicService.ungreat(circleTopic, reply);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("操作过于频繁");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }


    }

    @Operation(summary = "评论", description = "评论")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
            @Parameter(name = "uid", description = "用户id", required = true),
            @Parameter(name = "content", description = "评论内容", required = true),
            @Parameter(name = "replyTo", description = "回复对象用户id"),
            @Parameter(name = "operateType", description = "0-用户回复 1-平台回复"),
            @Parameter(name = "replyId", description = "回复id")
    })
    @RequestMapping(value = "/topic/reply", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult replyTopic(@RequestParam(value = "id") Long id,
                                 @RequestParam(value = "uid") String uid,
                                 @RequestParam(value = "content") String content,
                                 @RequestParam(value = "replyTo", required = false) String replyTo,
                                 @RequestParam(value = "operateType", required = false) Integer operateType,
                                 @RequestParam(value = "replyId", required = false) Long replyId) {
        try {
            blacklistService.checkLimit(uid);
            CircleTopic circleTopic = circleTopicService.getById(id);
            if (circleTopic == null) {
                return AjaxResult.error("对象信息不存在");
            }
            if (circleTopic.getDelFlag() != null && circleTopic.getDelFlag() == 1) {
                return AjaxResult.error("该动态已被删除！");
            }

            long now = System.currentTimeMillis();

            circleTopic.setReplyNum(circleTopic.getReplyNum() + 1);
            circleTopic.setLastReplyTime(now);

            CircleTopicReply reply = new CircleTopicReply();
            reply.setCreateTime(now);
            reply.setUid(uid);
            reply.setDelFlag(0);
            reply.setReplyType(TopicReplyTypeEnum.REPLY.value());
            reply.setTopFlag(0);
            reply.setContent(content);
            reply.setReplyTo(replyTo);
            if (uid.equals(circleTopic.getUid()) && StringUtils.isEmpty(replyTo)) {
                reply.setReadFlag(1);
            } else {
                if (!StringUtils.isEmpty(replyTo) && uid.equals(replyTo)) {
                    reply.setReadFlag(1);
                } else {
                    reply.setReadFlag(0);
                }
            }
            reply.setTopicId(id);
            reply.setReplyId(replyId);
            reply.setOperateType(operateType == null ? 0 : operateType);
            circleTopicService.save(circleTopic, reply);


            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());

        }
    }

    @Operation(summary = "删除我的评论", description = "删除我的评论")
    @Parameters({
            @Parameter(name = "id", description = "评论id", required = true),
            @Parameter(name = "uid", description = "用户id", required = true)
    })
    @RequestMapping(value = "/topic/my/reply/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult deleteMyReply(@RequestParam(value = "id") Long id,
                                    @RequestParam(value = "uid") String uid) {
        CircleTopicReply reply = circleTopicReplyService.selectById(id);
        if (reply == null) {
            return AjaxResult.error("对象信息不存在");
        }
        if (!reply.getUid().equals(uid)) {
            return AjaxResult.error("非法请求");
        }
        reply.setDelFlag(1);
        circleTopicReplyService.save(reply);

        CircleTopic circleTopic = circleTopicService.getById(reply.getTopicId());
        circleTopic.setReplyNum(circleTopic.getReplyNum() - 1);
        circleTopicService.update(circleTopic);
        return AjaxResult.success();
    }

    @Operation(summary = "删除评论（后台管理）", description = "删除评论（后台管理）")
    @Parameters({
            @Parameter(name = "id", description = "评论id", required = true),
            @Parameter(name = "operator", description = "后台用户id", required = true)
    })
    @RequestMapping(value = "/topic/reply/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult deleteReply(@RequestParam(value = "id") Long id) {
        CircleTopicReply reply = circleTopicReplyService.selectById(id);
        if (reply == null) {
            return AjaxResult.error("对象信息不存在");
        }
        //防止多次删除操作
        if (reply.getDelFlag() == 1) {
            return AjaxResult.success();
        }
        reply.setDelFlag(1);
        reply.setDelOperator(SecurityUtils.getUsername());
        reply.setDelOperTime(System.currentTimeMillis());
        circleTopicReplyService.save(reply);

        CircleTopic circleTopic = circleTopicService.getById(reply.getTopicId());
        circleTopic.setReplyNum(circleTopic.getReplyNum() - 1);
        circleTopicService.update(circleTopic);
        return AjaxResult.success();
    }


    @Operation(summary = "评论置顶", description = "评论置顶")
    @Parameters({
            @Parameter(name = "id", description = "评论id", required = true),
            @Parameter(name = "topFlag", description = "1-置顶，0-取消置顶", required = true)
    })
    @RequestMapping(value = "/topic/reply/top", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult topReply(@RequestParam(value = "id") Long id,
                               @RequestParam(value = "topFlag") Integer topFlag) {
        CircleTopicReply reply = circleTopicReplyService.selectById(id);
        if (reply == null) {
            return AjaxResult.error("对象信息不存在");
        }
        reply.setTopFlag(topFlag);
        reply.setTopUpdator(SecurityUtils.getUsername());
        reply.setTopTime(System.currentTimeMillis());
        circleTopicReplyService.save(reply);
        return AjaxResult.success();
    }

    @Operation(summary = "获取动态点赞或回复列表", description = "获取动态点赞或回复列表")
    @Parameters({
            @Parameter(name = "id", description = "动态id", required = true),
            @Parameter(name = "type", description = "类型 0：点赞 1：回复", required = true),
            @Parameter(name = "pageNum", description = "页码", example = "1"),
            @Parameter(name = "rows", description = "条数", example = "10")
    })
    @RequestMapping(value = "/topic/communication/list", method = RequestMethod.GET)
    @ResponseBody
    public TableDataInfo getTopicCommunicationPage(@RequestParam(value = "topicId") Long id,
                                                   @RequestParam(value = "type") Integer type,
                                                   @RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer rows) {
        // 使用 LambdaQueryWrapper 构造查询条件
        LambdaQueryWrapper<CircleTopicReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CircleTopicReply::getDelFlag, 0)
                .eq(CircleTopicReply::getTopicId, id)
                .eq(CircleTopicReply::getReplyType, type);

// 设置排序和分页
        Page<CircleTopicReply> topicReplyPage = new Page<>(pageNum, rows);
        topicReplyPage.addOrder(new OrderItem("top_flag", false), new OrderItem("create_time", false));

// 执行分页查询
        topicReplyPage = circleTopicReplyService.page(topicReplyPage, wrapper);


        List<ReplyItem> replyItemList = new ArrayList<>();
        if (topicReplyPage != null && topicReplyPage.getRecords() != null) {
            Set<String> uidSet = new HashSet<>();
            for (CircleTopicReply reply : topicReplyPage.getRecords()) {
                uidSet.add(reply.getUid());
                if (StringUtils.isNotBlank(reply.getReplyTo())) {
                    uidSet.add(reply.getReplyTo());
                }
                replyItemList.add(mapper.map(reply, ReplyItem.class));
            }
            fillReplyUserInfo(replyItemList, uidSet);
        }


        TableDataInfo result = new TableDataInfo(replyItemList, topicReplyPage.getTotal());
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        return result;

    }

    /**
     * 获取相关用户资料，完善返回列表
     *
     * @param replyItemList
     * @param uidSet
     */
    private void fillReplyUserInfo(List<ReplyItem> replyItemList, Set<String> uidSet) {
        Map<String, UserDetail> userDetailMap = authServiceExt.getUserMapByUidList(Lists.newArrayList(uidSet));
        UserDetail replyUser;
        for (ReplyItem replyItem : replyItemList) {
            replyUser = userDetailMap.get(replyItem.getUid());
            replyItem.setAvatar(replyUser.getPortrait());
            replyItem.setName(replyUser.getName());

            if (StringUtils.isNotBlank(replyItem.getReplyTo())) {
                replyUser = userDetailMap.get(replyItem.getReplyTo());
                if (replyUser != null) {
                    replyItem.setReplyToName(replyUser.getName());
                }
            }
        }
    }
}